import React, { useEffect, useContext, useState, useCallback } from 'react';
import {
  Form,
  Input,
  Select,
  Radio,
  InputNumber,
  Divider,
  Pagination,
  message,
  Button,
  Tooltip,
} from 'antd';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import { IntentionLibraryInfo } from '../../schema/IntentionLibrary';
import { getIntentions } from '../../servers/servers';
import { cloneDeep, debounce } from 'lodash';

const Option = Select.Option;

/**
 * 信息收集组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-信息收集组件
 */
const InfoCollectionComponent: React.FC = () => {
  const [form] = useForm();
  // Table loading状态
  // const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  // const [pageSize, setPageSize] = useState<number>(6);
  const pageSize = 6;
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [intentionList, setIntentionList] = useState<IntentionLibraryInfo[]>([]);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');
  const { versionId, selectedData, onInputChange, nodeDataArray } = useContext(InspectorContext);
  /**信息数组clone，页面表单用：将字段名改为value和label对应值用于select */
  const intentionArrayItem = cloneDeep(selectedData.intention).map((item: any) => {
    return { value: item.intentionId, label: item.text };
  });

  /**
   * Table数据加载
   */
  const initIntentions = useCallback(async () => {
    // setTableLoading(true);
    try {
      const res = await getIntentions({
        pageNo: current,
        pageSize,
        versionId,
        intentionName: searchText,
      });
      if (res.code === 0) {
        setIntentionList(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('initIntentions -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    // setTableLoading(false);
  }, [current, searchText, versionId]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    initIntentions();
  }, [initIntentions]);

  useEffect(() => {
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    console.log(
      '✅form数据-selectedData-信息收集组件',
      selectedData,
      '👇timeoutScriptArray',
      selectedData.timeoutScriptArray
    );

    form.setFieldsValue(selectedData);
    // 渲染就验证表单
    setTimeout(() => {
      form.validateFields();
      // .then()
      // .catch(errorInfo => {
      //   console.log(errorInfo, "999888****");
      // });
    }, 10);
  }, [form, selectedData]);

  return (
    <>
      <Form
        layout="vertical"
        form={form}
        initialValues={{
          intentionArrayItem: intentionArrayItem,
          timeoutFollowUpStateVal: 5,
          timeoutScriptArray: [],
        }}
      >
        <Form.Item
          label="信息收集组件名称"
          name="title"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 10,
              message: '仅支持输入10个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            maxLength={10}
            onBlur={e => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item
          label="话术内容"
          name="script"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 500,
              message: '仅支持输入500个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input.TextArea
            maxLength={500}
            onBlur={e => {
              onInputChange('script', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item
          label="变量名称"
          name="variableName"
          rules={[{ required: true, whitespace: true }]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            placeholder="请输入需要收集信息的变量名称"
            // onChange={e => {
            //   onInputChange("variableName", e.target.value, e.type === "blur");
            // }}
            onBlur={e => {
              onInputChange('variableName', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        {/* 意图：单选，按多选方便后续扩充*/}
        {/* intentionArrayItem */}
        <Form.Item
          label="关联意图"
          name="intentionArrayItem"
          //  mode="multiple" // 多选可变成数组，参考意图组件
          rules={[{ required: true, message: '请输入需要关联的意图' }]}
        >
          <Select
            showSearch
            placeholder="请输入需要关联的意图"
            labelInValue
            allowClear
            // value={intentionArrayItem}
            getPopupContainer={triggerNode => triggerNode.parentElement}
            onSearch={debounce(text => {
              setCurrent(1);
              setSearchText(text.trim());
            }, 700)}
            filterOption={false}
            onChange={(obj: any) => {
              if (obj) {
                onInputChange(
                  'intention',
                  /**将字段名改为intentionId和text */
                  [{ intentionId: obj.value, text: obj.label }],
                  true
                );
              } else {
                onInputChange('intention', [], true);
              }
            }}
            /**自定义下拉区域 */
            dropdownRender={menu => (
              <div>
                {menu}
                {total > 0 && (
                  <>
                    <Divider style={{ margin: '4px 0' }} />
                    <div style={{ padding: '8px', textAlign: 'center' }}>
                      <Pagination
                        simple
                        current={current}
                        total={total}
                        onChange={current => {
                          setCurrent(current);
                        }}
                      />
                    </div>
                  </>
                )}
              </div>
            )}
          >
            {/* 意图列表 */}
            {intentionList.map(item => {
              return (
                <Option key={item.intentionId} value={item.intentionId}>
                  {item.intentionName}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item label="重复次数">
          <Radio.Group
            value={selectedData.numberOfAttempts}
            onChange={e => {
              onInputChange('numberOfAttempts', e.target.value, true);
            }}
          >
            <Radio value={1}>1</Radio>
            <Radio value={2}>2</Radio>
          </Radio.Group>
        </Form.Item>
        {/* 超时设置（最多4次）--4.8改版后*/}
        {selectedData.timeoutScriptArray && (
          <>
            <Divider />
            {/* 第1-3次超时：超时设置(时间、话术) */}
            <Form.List name="timeoutScriptArray">
              {(fields, { add, remove }) => (
                <>
                  <Form.Item
                    className="form-list-item-tit"
                    required
                    label="超时静默设置"
                    style={{ flexDirection: 'row' }}
                  >
                    <Tooltip title={fields.length > 2 ? '最多4次超时设置' : '添加超时设置'}>
                      <Button
                        type="link"
                        onClick={() => {
                          // 添加超时设置
                          const arr = cloneDeep(selectedData.timeoutScriptArray);
                          arr.push({
                            timeout: 5,
                            script: null,
                          });
                          onInputChange('timeoutScriptArray', arr, true);
                          add();
                        }}
                        disabled={fields.length > 2 ? true : false}
                      >
                        <PlusCircleOutlined className="form-list-btn-icon" />
                      </Button>
                    </Tooltip>
                  </Form.Item>
                  {/* 循环体-内部 */}
                  {fields.map((field, index) => (
                    <div key={field.key} className="form-list-item-wrap unselect-words">
                      <Form.Item
                        required
                        label={`第${index + 1}次静默达到`}
                        className="form-list-item-ctn"
                        style={{ flexDirection: 'row' }}
                      >
                        <Form.Item
                          {...field}
                          noStyle
                          name={[field.name, 'timeout']}
                          fieldKey={[field.fieldKey, 'timeout']}
                        >
                          <InputNumber
                            min={1}
                            max={100}
                            precision={0}
                            size="middle"
                            placeholder="1-100"
                            className="timeout-number-input"
                            parser={(value: any) => value || 5}
                            defaultValue={5}
                            onBlur={e => {
                              const val = Number(e.target.value) || 5;
                              const arr = cloneDeep(selectedData.timeoutScriptArray);
                              arr[index].timeout = val;
                              onInputChange('timeoutScriptArray', arr, true);
                            }}
                          />
                        </Form.Item>
                        <span className="form-item-last-txt">秒，则播放超时话术</span>
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label=""
                        name={[field.name, 'script']}
                        fieldKey={[field.fieldKey, 'script']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            max: 500,
                            message: `请输入第${index + 1}次超时话术`,
                          },
                        ]}
                        getValueFromEvent={event => {
                          return event.target.value.replace(/\s+/g, '');
                        }}
                      >
                        <Input.TextArea
                          maxLength={500}
                          placeholder="请输入超时话术"
                          onBlur={e => {
                            const value = e.target.value;
                            const arr = cloneDeep(selectedData.timeoutScriptArray);
                            arr[index].script = value;
                            onInputChange('timeoutScriptArray', arr, true);
                          }}
                        />
                      </Form.Item>
                      <Tooltip title="删除设置">
                        <MinusCircleOutlined
                          className="form-list-btn-icon  btn-delete"
                          onClick={() => {
                            const arr = cloneDeep(selectedData.timeoutScriptArray);
                            if (index <= arr.length - 1) {
                              // 删除的数据，在数组中存在。需要从数组删除，更新数组。
                              // 更新数据结构
                              arr.splice(index, 1);
                              onInputChange('timeoutScriptArray', arr, true);
                            }
                            remove(field.name);
                          }}
                        />
                      </Tooltip>
                    </div>
                  ))}
                </>
              )}
            </Form.List>
            {/* 第4次超时：节点跳转 */}
            <div className="form-list-last-item unselect-words">
              <Form.Item
                required
                className="form-list-item-ctn"
                style={{ flexDirection: 'row' }}
                label={`第${selectedData.timeoutScriptArray?.length + 1}次静默达到`}
              >
                <Form.Item name="timeoutFollowUpStateVal" noStyle>
                  <InputNumber
                    min={1}
                    max={100}
                    precision={0}
                    placeholder="1-100"
                    className="timeout-number-input"
                    parser={(value: any) => value || 5}
                    defaultValue={5}
                    onBlur={e => {
                      const val = Number(e.target.value) || 5;
                      onInputChange('timeoutFollowUpStateVal', val, true);
                    }}
                  />
                </Form.Item>
                <span className="form-item-last-txt">秒，则跳转节点</span>
              </Form.Item>
              <Form.Item
                name="timeoutFollowUpAct"
                rules={[
                  {
                    required: true,
                    message: '请选择跳转节点',
                  },
                ]}
              >
                <Select
                  placeholder="请选择跳转节点"
                  allowClear
                  labelInValue
                  // value={selectedData.timeoutFollowUpAct}
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  onChange={obj => {
                    console.log('❌跳转节点********', obj);
                    onInputChange('timeoutFollowUpAct', obj, true);
                  }}
                >
                  {nodeDataArray.map((item: any) => {
                    return (
                      <Option value={item.key} key={item.key} disabled={item.key === 0}>
                        {item.title}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </div>
          </>
        )}
      </Form>
    </>
  );
};

export default InfoCollectionComponent;
